#!/usr/bin/python3
# by Sun Smallwhite <niasw@pku.edu.cn>(https://github.com/niasw)

import re
import numpy
import sw.io.loadJSON
import sw.io.loadCSV

def histIdxMap(history,indexstart=0):
  '''
# History Index Mapping, adds index indent
  '''
  for itc in range(0,len(history[-1])):
    history[-1][itc]['clus']=[p+indexstart for p in history[-1][itc]['clus']];
  return history;

def clus2vec(clusters,indexstart=0):
  '''
# Transfer clusters into vector format.
  '''
  tmp=list();
  clusvec=list();
  for it1 in range(0,len(clusters)):
    for it2 in clusters[it1]:
      tmp.append((it2,it1));
  tmpres=sorted(tmp,key=lambda unit:unit[0]);
  clusid=list(numpy.unique([it1[1] for it1 in tmpres]));
  for it1 in tmpres:
    clusvec.append(clusid.index(it1[1])+indexstart);
  return clusvec;

def vec2csv(clusvec,filename):
  '''
# Write vector format data into a csv file.
  '''
  filename=re.sub('.*[/\\\]','',filename);
  print('Saving File: '+'../out/'+filename+'.csv');
  newf=open('../out/'+filename+'.csv','w');
  for it in clusvec:
    newf.write(str(it)+'\n');
  newf.close();

def webOfSciNode2csvMat(webOfSciNodes,dtype='file',extname=''):
  '''
# Transfer node file (generated by sw.io.loadTSV.webOfScience) into csv matrix (sparse_coo)
# dtype: file/data
  '''
  linkf=None;
  if (dtype=='file'):
    nodes=sw.io.loadJSON.loadJSON(webOfSciNodes);
    webOfSciNodes=re.sub('.*[/\\\]','',webOfSciNodes);
    print('Saving File: '+'../out/linkmat.'+webOfSciNodes+'.csv');
    linkf=open('../out/linkmat.'+webOfSciNodes+'.csv','w');
  elif (dtype=='data'):
    nodes=webOfSciNodes;
    extname=re.sub('.*[/\\\]','',extname);
    print('Saving File: '+'../out/linkmat.'+extname+'.csv');
    linkf=open('../out/linkmat.'+extname+'.csv','w');
  else:
    raise(Exception('Warning: invalid dtype parameter: '+dtype+'.'));
  for it1 in range(0,len(nodes)):
    for it2 in range(0,len(nodes[it1]['citation'])):
      linkf.write(str(nodes[it1]['citation'][it2]['newid'])+','+str(it1)+'\n');
  linkf.close();
  
